package com.das.mechanic_base.adapter.main;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieCompositionFactory;
import com.airbnb.lottie.LottieTask;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.bumptech.glide.request.transition.Transition;
import com.das.mechanic_base.R;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3RouterCenter;
import com.das.mechanic_base.bean.main.CarPicAndColorBean;
import com.das.mechanic_base.mvp.view.camera.X3MainCarCutActivity;
import com.das.mechanic_base.utils.LanguageUtiles;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3GlideNewUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.das.mechanic_base.widget.X3AppPrograssView;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static android.view.View.GONE;

public class X3BottomHomeCarAndColorAdapter extends RecyclerView.Adapter<X3BottomHomeCarAndColorAdapter.BottomHomeCarAndColorHolder> {

    private Context mContext;

    private List<CarPicAndColorBean> mList;

    private String carNum;

    private long carId;

    private int currentPrograss = 0;

    private boolean isToast;

    private long colorId,carPicTempletId;

    private List<Boolean> sList;

    private RecyclerView mRecyclerView;
    
    public X3BottomHomeCarAndColorAdapter(Context mContext,RecyclerView mRecyclerView) {
        this.mContext = mContext;
        this.mRecyclerView = mRecyclerView;
        this.mList = new ArrayList<>();
        this.sList = new ArrayList<>();
    }

    public void changeCarAndColor(List<CarPicAndColorBean> mList,String carNum,long colorId,long carPicTempletId) {
        this.mList = mList;
        this.carNum = carNum;
        this.colorId = colorId;
        this.carPicTempletId = carPicTempletId;
        this.sList.clear();
        for (int i = 0; i < mList.size(); i++) {
            CarPicAndColorBean picAndColorBean = mList.get(i);
            if (picAndColorBean == null) {
                sList.add(false);
                continue;
            }
            sList.add(carPicTempletId == picAndColorBean.getCarPicTempletId() && colorId == picAndColorBean.getColorId());
        }
        notifyDataSetChanged();
    }

    public void changeSelectColor(long colorId,long carPicTempletId) {
        this.colorId = colorId;
        this.carPicTempletId = carPicTempletId;
        this.sList.clear();
        for (int i = 0; i < mList.size(); i++) {
            CarPicAndColorBean picAndColorBean = mList.get(i);
            if (picAndColorBean == null) {
                sList.add(false);
                continue;
            }
            sList.add(carPicTempletId == picAndColorBean.getCarPicTempletId() && colorId == picAndColorBean.getColorId());
        }
        notifyDataSetChanged();
    }

    public void sendCarId(long carId) {
        this.carId = carId;
    }

    public void changeLastCarCut(List<CarPicAndColorBean> mList) {
        this.mList = mList;
        this.isToast = true;
        notifyItemChanged(mList.size() - 1);
    }

    public void changeNoToast() {
        this.isToast = false;
    }

    /**
     * 改变进度值
     * @param currentPrograss
     */
    public void changePrograss(double currentPrograss) {
        this.currentPrograss = (int) (currentPrograss * 100);
        if (mRecyclerView != null){
            mRecyclerView.post(new Runnable() {
                @Override
                public void run() {
                    notifyItemChanged(mList.size() - 1);
                }
            });
        } else {
            notifyItemChanged(mList.size() - 1);
        }
    }

    @NonNull
    @Override
    public BottomHomeCarAndColorHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new BottomHomeCarAndColorHolder(LayoutInflater.from(mContext).inflate(R.layout.x3_car_and_color_item,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull BottomHomeCarAndColorHolder holder, int position) {
        if (X3StringUtils.isListEmpty(mList)) {
            return;
        }
        if (sList.get(position)) {
            holder.itemView.setBackground(ContextCompat.getDrawable(mContext,R.drawable.x3_car_and_color_select_shape));
        }else {
            holder.itemView.setBackground(ContextCompat.getDrawable(mContext,R.drawable.x3_car_and_color_shape));
        }

        if (position == mList.size() - 1) {
            Log.e("pic_op_","position == mList.size() - 1");
            holder.iv_car.setVisibility(View.INVISIBLE);
            holder.lv_car.setVisibility(View.INVISIBLE);

            holder.tv_reload.setText(LanguageUtiles.appContext.getString(R.string.x3_reUpload_img));

            CarPicAndColorBean carPicAndColorBean = mList.get(position);

            String resourceUrl = carPicAndColorBean.getResourceUrl();
            if (!X3StringUtils.isEmpty(carPicAndColorBean.getCarNum())) {
                // 说明之前上传过图
                holder.iv_take.setVisibility(GONE);
                holder.rl_reload.setVisibility(View.VISIBLE);
                holder.tv_prograss.setText(currentPrograss + "%");
                holder.av_view.setCurrentPrograss(currentPrograss);

                if (!X3StringUtils.isEmpty(resourceUrl)) {
                    if (resourceUrl.startsWith("/")) {
                        holder.iv_car.setVisibility(GONE);
                        holder.rl_load.setVisibility(View.VISIBLE);

                        // 本地图片
                        Glide.with(mContext).load(resourceUrl).apply(
                                new RequestOptions().placeholder(R.mipmap.x3_car_no_color_and_pic_icon).skipMemoryCache(false).dontAnimate()
                        ).into(holder.iv_cut_car);
                    }else {
                        // 网络图片
                        Glide.with(mContext).load(X3StringUtils.getImageUrl(resourceUrl)).apply(
                                new RequestOptions().placeholder(R.mipmap.x3_car_no_color_and_pic_icon).skipMemoryCache(false).dontAnimate()
                        ).into(new ImageViewTarget<Drawable>(holder.iv_car) {
                            @Override
                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                super.onResourceReady(resource, transition);
                                if (iOnClickCarPic != null) {
                                    iOnClickCarPic.iOnCancelAnim();
                                }
                                if (isToast) {
                                    X3ToastUtils.showMessage(mContext.getString(R.string.x3_car_cut_success));
                                    isToast = false;
                                }
                                holder.iv_car.setVisibility(View.VISIBLE);
                                holder.rl_load.setVisibility(GONE);
                                holder.iv_car.setImageDrawable(resource);
                            }

                            @Override
                            protected void setResource(@Nullable Drawable resource) {

                            }
                        });
                    }
                }

                holder.itemView.setOnClickListener(v -> {
                    if (iOnClickCarPic != null) {
                        iOnClickCarPic.iOnClickCarPicId(mList.get(position),"",position);
                    }
                });

                holder.rl_reload.setOnClickListener(v -> {
                    XXPermissions.with(mContext)
                            .permission(Permission.Group.STORAGE)
                            .request((permissions, all) -> {
                                if(all){
                                    Bundle bundle = new Bundle();
                                    bundle.putLong("carId",carId);
                                    bundle.putString("carNum",carNum);
                                    X3RouterCenter.startNavigate(X3AppRouterConstants.Router.MAIN_CUT,bundle);
                                }else {
                                    XXPermissions.startPermissionActivity(mContext);
                                }
                            });
                });

            }else {
                holder.iv_car.setVisibility(View.INVISIBLE);
                holder.lv_car.setVisibility(View.INVISIBLE);
                if (X3StringUtils.isEmpty(resourceUrl)) {
                    // 说明没有上传过
                    holder.iv_take.setVisibility(View.VISIBLE);
                    holder.rl_reload.setVisibility(GONE);
                    holder.lv_car.setVisibility(GONE);
                    holder.rl_load.setVisibility(GONE);
                    if (iOnClickCarPic != null) {
                        iOnClickCarPic.iOnCancelAnim();
                    }

                    holder.itemView.setOnClickListener(v -> {
                        // TODO 跳转到车辆切割页面
                        XXPermissions.with(mContext)
                                .permission(Permission.Group.STORAGE)
                                .request((OnPermissionCallback) (permissions, all) -> {
                                    if(all){
                                        Bundle bundle = new Bundle();
                                        bundle.putLong("carId",carId);
                                        bundle.putString("carNum",carNum);
                                        X3RouterCenter.startNavigate(X3AppRouterConstants.Router.MAIN_CUT,bundle);
                                    }else {
                                        XXPermissions.startPermissionActivity(mContext);
                                    }
                                });
                    });
                }else {
                    // 正在上传中
                    holder.iv_take.setVisibility(GONE);
                    holder.rl_load.setVisibility(View.VISIBLE);
                    holder.rl_reload.setVisibility(View.VISIBLE);

                    // resourceUrl
                    Glide.with(mContext).load(resourceUrl).apply(
                            new RequestOptions().placeholder(R.mipmap.x3_car_no_color_and_pic_icon).skipMemoryCache(false).dontAnimate()
                    ).into(holder.iv_cut_car);

                    holder.tv_prograss.setText(currentPrograss + "%");
                    holder.av_view.setCurrentPrograss(currentPrograss);

                    holder.itemView.setOnClickListener(v -> {
                        CarPicAndColorBean picAndColorBean = mList.get(position);
                        picAndColorBean.setWaitingForCarPicTemplet(true);
                        if (iOnClickCarPic != null) {
                            iOnClickCarPic.iOnClickCarPicId(picAndColorBean,"",position);
                        }
                    });

                    holder.rl_reload.setOnClickListener(v -> {
                        XXPermissions.with(mContext)
                                .permission(Permission.Group.STORAGE)
                                .request((permissions, all) -> {
                                    if(all){
                                        Intent intent = new Intent(mContext, X3MainCarCutActivity.class);
                                        intent.putExtra("carId",carId);
                                        intent.putExtra("carNum",carNum);
                                        mContext.startActivity(intent);
                                    }else {
                                        XXPermissions.startPermissionActivity(mContext);
                                    }
                                });

                    });
                }
            }

        }else {
            holder.rl_reload.setVisibility(GONE);
            holder.iv_take.setVisibility(GONE);
            holder.rl_load.setVisibility(GONE);

            CarPicAndColorBean picAndColorBean = mList.get(position);

            String colourRgb = picAndColorBean.getColourRgb();
            String colourRgbBak = picAndColorBean.getColourRgbBak();


            String type = picAndColorBean.getType();
            String carMove;
            if ("T_JSON".equals(type)) {
                carMove = X3FileUtils.readBeanFromSdCard(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + picAndColorBean.getColourRgb() + "/carMove.json");
                //String carMove = "";
                if (X3StringUtils.isEmpty(carMove)) {
                    holder.iv_car.setImageResource(R.mipmap.x3_car_no_color_and_pic_icon);
                    holder.iv_car.setVisibility(View.VISIBLE);
                    holder.lv_car.setVisibility(GONE);
                } else {
                    holder.iv_car.setVisibility(GONE);
                    holder.lv_car.setVisibility(View.VISIBLE);
//                    holder.lv_car.setRepeatCount(-1);
                    holder.lv_car.setImageAssetDelegate(asset -> {
                        FileInputStream fileInputStream = null;
                        try {
                            String lp = X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + picAndColorBean.getColourRgb() +
                                    "/images/" + asset.getFileName();
//                            Log.e("pic_op_","开始加载图片 lp = " + lp);
                            fileInputStream = new FileInputStream(lp);
                            //把流转化为Bitmap图片
                            return BitmapFactory.decodeStream(fileInputStream);

                        } catch (Exception e) {
                            //Log.e("SSSS","获取图片报错："+e.toString());
//                            Log.e("pic_op_","获取图片报错：");
                        } finally {
                            if (fileInputStream != null) {
                                try {
                                    fileInputStream.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        return null;
                    });

                    LottieTask<LottieComposition> lottieMoveTask = LottieCompositionFactory.fromJsonString(carMove, "move" + colourRgbBak + colourRgb + position);

                    Log.e("pic_op_","lotty_key = " + carMove);
                    Log.e("pic_op_","lotty_cache_key = " + "move" + colourRgbBak + colourRgb + position);


                    lottieMoveTask.addListener(result -> {
                        holder.lv_car.setComposition(result);
                        holder.lv_car.setProgress(0);
                        holder.lv_car.playAnimation();
                    });

                }

            }else {
                carMove = "";
                holder.iv_car.setVisibility(View.VISIBLE);
                holder.lv_car.setVisibility(View.INVISIBLE);
                String picUrl = picAndColorBean.getResourceUrl();
                X3GlideNewUtils.loadNormalImage(mContext,X3StringUtils.getImageUrl(picUrl),holder.iv_car,R.mipmap.x3_car_no_color_and_pic_icon);
                Log.e("pic_op_","carMove = 空");
            }

            holder.itemView.setOnClickListener(view -> {
                if (iOnClickCarPic != null) {
                    iOnClickCarPic.iOnClickCarPicId(mList.get(position),carMove,position);
                }
            });
        }
    }

    IOnClickCarPic iOnClickCarPic;

    public void setiOnClickCarPic(IOnClickCarPic iOnClickCarPic) {
        this.iOnClickCarPic = iOnClickCarPic;
    }

    public interface IOnClickCarPic{
        void iOnClickCarPicId(CarPicAndColorBean picAndColorBean,String carMove,int position);

        /**
         * 取消动画
         */
        void iOnCancelAnim();
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    class BottomHomeCarAndColorHolder extends RecyclerView.ViewHolder {
        ImageView iv_car;
        LottieAnimationView lv_car;
        View v_shape;
        ImageView iv_take;
        RelativeLayout rl_load;
        ImageView iv_cut_car;
        X3AppPrograssView av_view;
        RelativeLayout rl_reload;
        TextView tv_prograss;
        TextView tv_reload;
        public BottomHomeCarAndColorHolder(@NonNull View itemView) {
            super(itemView);
            iv_car = itemView.findViewById(R.id.iv_car);
            lv_car = itemView.findViewById(R.id.lv_car);
            v_shape = itemView.findViewById(R.id.v_shape);
            iv_take = itemView.findViewById(R.id.iv_take);
            rl_load = itemView.findViewById(R.id.rl_load);
            iv_cut_car = itemView.findViewById(R.id.iv_cut_car);
            av_view = itemView.findViewById(R.id.av_view);
            rl_reload = itemView.findViewById(R.id.rl_reload);
            tv_prograss = itemView.findViewById(R.id.tv_prograss);
            tv_reload = itemView.findViewById(R.id.tv_reload);
        }
    }
}
